<script setup>
import { ref, onMounted, computed, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { apiRequest } from '@/utils/apiRequest'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import CommonLayout from '../components/CommonLayout.vue'

// 定义表格数据和分页信息
const userList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const loading = ref(false)

// 搜索表单数据
const searchForm = reactive({
  username: '',
  role: '-1',
  status: '-1'
})

// 获取用户列表 - 调用真实API
const getUserList = async (params) => {

  try {
    let url = '/api/Users'
    
    // 构建查询参数
    const queryParams = new URLSearchParams()
    queryParams.append('page', params.page)
    queryParams.append('pageSize', params.pageSize)
    
    if (params.username) {
      queryParams.append('username', params.username)
    }
    
    if (params.role && params.role !== '-1') {
      queryParams.append('role', params.role)
    }
    
    if (params.status && params.status !== '-1') {
      queryParams.append('status', params.status)
    }
    
    // 如果有查询参数，拼接URL
    if (queryParams.toString()) {
      url = `${url}?${queryParams.toString()}`
    }
    
    // 调用真实API
    const response = await apiRequest.get(url)

    // 处理ASP.NET Core返回的格式
    const dataArray = response.data?.$values || response.data || []
    // 格式化返回数据以匹配前端期望的结构
    // 确保status字段是数字类型
    const formattedData = dataArray.map(user => ({
      ...user,
      status: Number(user.status) // 确保status是数字类型
    }))
    return {
      data: {
        items: formattedData,
        total: formattedData.length
      }
    }
  } catch (error) {
    console.error('Failed to fetch users:', error)
    ElMessage.error('获取用户列表失败: ' + error.message)
    throw error
  }
}

const updateUserStatus = async (id, statusValue) => {
  try {
    if (!id) {
      throw new Error('用户ID不能为空')
    }
    // 提取并确保状态值是布尔类型
    const status = typeof statusValue === 'object' ? !!statusValue.status : !!statusValue;
    
    
    // 直接发送布尔值作为请求体
    const response = await apiRequest.patch(`/api/Users/${id}/status`, status, {
      headers: { 'Content-Type': 'application/json' },
      validateStatus: (status) => true // 确保所有状态码都被返回
    })
    
    
    // 对于204 No Content响应，认为成功
    return { success: response.status === 204 }
  } catch (error) {
    console.error(`Failed to update status for user ${id || 'undefined'}:`, error)
    
    ElMessage.error('更新用户状态失败: ' + (error.response?.data?.message || error.message))
    throw error
  }
}

const deleteUser = async (id) => {
  try {
    
    // 调用真实API
    await apiRequest.delete(`/api/Users/${id}`)
    return { success: true }
  } catch (error) {
    console.error(`Failed to delete user ${id}:`, error)
    ElMessage.error('删除用户失败: ' + error.message)
    throw error
  }
}

// 搜索用户
const handleSearch = () => {
  currentPage.value = 1
  fetchUserList()
}

// 重置搜索
const handleReset = () => {
  searchForm.username = ''
  searchForm.role = '-1'
  searchForm.status = '-1'
  currentPage.value = 1
  fetchUserList()
}

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true

  try {

    const response = await getUserList({
      page: currentPage.value,
      pageSize: pageSize.value,
      username: searchForm.username,
      role: searchForm.role,
      status: searchForm.status
    })

    userList.value = response.data.items
    total.value = response.data.total


  } catch (error) {
    ElMessage.error('获取用户列表失败: ' + error.message)
    console.error('Failed to fetch user list:', error)
  } finally {
    loading.value = false

  }
}

// 改变用户状态
const changeUserStatus = async (row, newStatus) => {
  try {
    if (!row || !row.id) {
      throw new Error('无效的用户数据')
    }
    
    await updateUserStatus(row.id, {
      status: newStatus
    })
    // 直接更新本地状态
    row.status = newStatus
    ElMessage.success('用户状态更新成功')
  } catch (error) {
    console.error(`Failed to change user ${row.id} status:`, error)
    ElMessage.error('更新用户状态失败: ' + error.message)
    // 恢复原来的状态
    row.status = !newStatus
  }
}

// 新增用户相关状态
const dialogVisible = ref(false)
const formRef = ref(null)
const form = ref({
  username: '',
  email: '',
  role: '普通用户',
  status: 1
})
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 编辑用户相关状态
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editForm = ref({})
const editRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 更新用户信息 - 调用真实API
const updateUser = async (id, params) => {
  try {
    if (!id) {
      throw new Error('用户ID不能为空')
    }
    
    
    // 格式化请求参数，只包含必要字段
    const formattedParams = {
      username: params.username,
      email: params.email,
      role: params.role,
      status: Number(params.status) // 确保status是数字类型
    }
    
    
    // 调用真实API
    const response = await apiRequest.put(`/api/Users/${id}`, formattedParams, {
      headers: { 'Content-Type': 'application/json' },
      validateStatus: (status) => true // 确保所有状态码都被返回
    })
    
    
    
    // 更新本地数据以保持同步
    const index = userList.value.findIndex(user => user.id === id)
    if (index !== -1) {
      userList.value[index] = { ...userList.value[index], ...formattedParams }
    }
    
    return { success: response.status >= 200 && response.status < 300 }
  } catch (error) {
    const errorMessage = error.response?.data?.message || error.message
    ElMessage.error('更新用户失败: ' + errorMessage)
    throw error
  }
}

// 打开编辑用户对话框
const handleEdit = (row) => {
  
  
  // 深拷贝用户数据到编辑表单
  editForm.value = { ...row }
  // 添加延迟确保数据完全拷贝后再显示对话框
  setTimeout(() => {
    
    editDialogVisible.value = true
    
    // 确认对话框状态
    
  }, 300) // 增加延迟时间到300ms
}

// 提交编辑用户表单
const submitEditForm = async () => {
  try {
    // 表单验证
    await editFormRef.value.validate()
    
    // 使用await等待updateUser完成
    await updateUser(editForm.value.id, editForm.value)
    ElMessage.success('编辑用户成功')
    editDialogVisible.value = false
    // 保持本地数据同步，无需重新加载列表
  } catch (error) {
    if (error.name === 'ValidationError') {
      // 表单验证失败，已经在表单中显示错误提示
      
      return
    }
    console.error('提交编辑表单失败:', error)
    ElMessage.error('编辑用户失败: ' + error.message)
  }
}

// 取消编辑用户
const cancelEditForm = () => {
  editDialogVisible.value = false
}

// 角色设置相关状态
const roleDialogVisible = ref(false)
const roleFormRef = ref(null)
const roleForm = ref({ id: '', role: '' })
const roleRules = {
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 打开角色设置对话框
const handleRole = (row) => {
  
  roleForm.value = { id: row.id, role: row.role }
  roleDialogVisible.value = true
}

// 提交角色设置表单
const submitRoleForm = async () => {
  try {
    // 表单验证
    await roleFormRef.value.validate()
    await updateUser(roleForm.value.id, { role: roleForm.value.role })
    ElMessage.success('角色设置成功')
    roleDialogVisible.value = false
    fetchUserList() // 重新加载列表
  } catch (error) {
    if (error.name === 'ValidationError') {
      // 表单验证失败，已经在表单中显示错误提示
      return
    }
    ElMessage.error('角色设置失败: ' + error.message)
  }
}

// 取消角色设置
const cancelRoleForm = () => {
  roleDialogVisible.value = false;
};

// 新增用户
const handleAddUser = () => {
  
  // 重置表单
  form.value = {
    username: '',
    email: '',
    role: '普通用户',
    status: 1
  }
  // 打开对话框
  dialogVisible.value = true
}

// 提交新增用户表单
const submitForm = async () => {
  try {
      // 表单验证
      await formRef.value.validate()
      // 调用真实API新增用户
      const newUser = await apiRequest.post('/api/Users', form.value)
      ElMessage.success('新增用户成功')
      dialogVisible.value = false
      fetchUserList() // 重新加载列表
  } catch (error) {
    if (error.name === 'ValidationError') {
      // 表单验证失败，已经在表单中显示错误提示
      return
    }
    ElMessage.error('新增用户失败: ' + error.message)
  }
}

// 取消新增用户
const cancelForm = () => {
  dialogVisible.value = false
}

// 编辑用户和角色设置函数已在上方定义

// 删除用户
const deleteUserConfirm = (row) => {
  ElMessageBox.confirm(
    `确定要删除用户 ${row.username} 吗?`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        await deleteUser(row.id)
        ElMessage.success('删除用户成功')
        fetchUserList() // 重新加载列表
      } catch (error) {
        ElMessage.error('删除用户失败: ' + error.message)
      }
    })
    .catch(() => {
      // 取消删除
    })
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchUserList()
}

const handleCurrentChange = (current) => {
  currentPage.value = current
  fetchUserList()
}

// 页面加载时获取用户列表
onMounted(() => {
  
  fetchUserList()
})
</script>

<template>
  <common-layout title="用户管理">
    <template #header-buttons>
      <el-button type="primary" @click="handleAddUser">
        <el-icon><Plus /></el-icon>
        新增用户
      </el-button>
    </template>

    <template #search-form>
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名" style="width: 260px;">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="角色" style="width: 260px;">
        <el-select v-model="searchForm.role" placeholder="请选择角色">
          <el-option label="全部" value="-1" />
          <el-option label="管理员" value="管理员" />
          <el-option label="普通用户" value="普通用户" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" style="width: 260px;">
        <el-select v-model="searchForm.status" placeholder="请选择状态">
          <el-option label="全部" value="-1" />
          <el-option label="启用" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item style="width: auto;">
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button @click="handleReset">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
      </el-form-item>
    </el-form>
    </template>

    <template #data-content>
    <!-- 用户列表 -->
    <el-table
      v-loading="loading"
      :data="userList"
      style="width: 100%"
      border
      stripe
    >
        <el-table-column prop="id" label="用户ID" width="80" />
        <el-table-column prop="username" label="用户名" width="180" />
        <el-table-column prop="email" label="邮箱" width="250" />
        <el-table-column prop="role" label="角色" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-switch
              :model-value="scope.row.status === 1"
              :active-value="true"
              :inactive-value="false"
              @change="(value) => changeUserStatus(scope.row, value ? 1 : 0)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="260" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="success" size="small" @click="handleRole(scope.row)">角色设置</el-button>
            <el-button type="danger" size="small" @click="deleteUserConfirm(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    </template>

    <!-- 新增用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="新增用户"
      width="500px"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role" placeholder="请选择角色">
            <el-option label="管理员" value="管理员" />
            <el-option label="普通用户" value="普通用户" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelForm">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑用户"
      width="500px"
      append-to-body
      :visible.sync="editDialogVisible"
    >
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="editForm.role" placeholder="请选择角色">
            <el-option label="管理员" value="管理员" />
            <el-option label="普通用户" value="普通用户" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="editForm.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelEditForm">取消</el-button>
          <el-button type="primary" @click="submitEditForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 角色设置对话框 -->
    <el-dialog
      v-model="roleDialogVisible"
      title="角色设置"
      width="400px"
    >
      <el-form :model="roleForm" :rules="roleRules" ref="roleFormRef" label-width="100px">
        <el-form-item label="角色" prop="role">
          <el-select v-model="roleForm.role" placeholder="请选择角色">
            <el-option label="管理员" value="管理员" />
            <el-option label="普通用户" value="普通用户" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelRoleForm">取消</el-button>
          <el-button type="primary" @click="submitRoleForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </common-layout>
</template>

<style scoped>
/* 原有样式被CommonLayout组件样式替代 */

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.search-form {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 5px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>